package com.zhangzhan.gulimallproduct.exception;

import com.zhangzhan.gulimallcommcon.exception.exception_enum.ExceptionEnum;
import com.zhangzhan.gulimallcommcon.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 张一恒
 * @version 1.0
 * @description:
 * @date 2024/6/15 21:40
 */
@RestControllerAdvice
@Slf4j
public class ProductExceptionHandler {

    /**
     * valid校验异常
     *
     * @param argumentNotValidException
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    private R handlerValidException(MethodArgumentNotValidException argumentNotValidException) {
        BindingResult bindingResult = argumentNotValidException.getBindingResult();
        Map<String, String> map = new LinkedHashMap<>();
        bindingResult.getFieldErrors().forEach(po -> {
            map.put(po.getField(), po.getDefaultMessage());
        });
        return R.error(ExceptionEnum.VALID_EXCEPTION.getCode(), ExceptionEnum.VALID_EXCEPTION.getMeg()).put("data", map);
    }

    /**
     * 服务器未知异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    private R handlerValidException(Exception e) {

        e.printStackTrace();

        return R.error(ExceptionEnum.UNNOW_EXCEPTION.getCode(), ExceptionEnum.UNNOW_EXCEPTION.getMeg()).put("data", e.getMessage());
    }

}
